#RequireAdmin
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=internet-radio-new.ico
#AutoIt3Wrapper_UseUpx=n
#AutoIt3Wrapper_Change2CUI=y
#AutoIt3Wrapper_Res_Comment=Automatically setup wifi for 802.1x protocol and then set a first available.  Check to make sure it's not changed.
#AutoIt3Wrapper_Res_Fileversion=1.0.0.0
#AutoIt3Wrapper_Res_Language=4105
#AutoIt3Wrapper_Res_requestedExecutionLevel=asInvoker
#AutoIt3Wrapper_Res_Field=Made by|Roger Grondin
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#cs
Windows Csd63 802.1x service for CSCPROVIDENCE
Version 1.1

Author: Roger Grondin

This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 GNU General Public License for more details.

You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

#ce


#include <include\Services.au3>
;#include <include\Wifi33a.au3>
#include <include\NativeWifi.au3>
#include <array.au3>

Global $MainLog = @ScriptDir & "\CSD63_set.log"
Global $sServiceName = 	"CSD63-802.1x"
Global $sDisplayName = 	"CSD63 802.1x Service"
Global $sDescription = 	"This service will set up the CSD63 wifi profile on board laptops and ensure that it stays at the top profile.  " & _
						"If a user either deletes the CSD63 profile or demotes it, the service will restore the profile and place it at the top.  " & _
						"If the hardware is switched off the NOVEL 802.1x logon is disabled."
Global $aDependency[1]
Global $aInterfaces
Global $pGuid
Global $sGuid

Local $Wlanapi_result

#cs
If @Compiled = 1 Then
    If _Service_QueryType($sServiceName) = 0 Then
        InstallService()
        Exit
    EndIf
Else
    _code()
EndIf
#ce

Switch @OSVersion
	Case "WIN_XP"
		ConsoleWrite("Windows XP detected"& @CRLF)
		logprint("Windows XP detected")
		;Set Depdendancy for service startup
		$aDependency[0] = ""

	Case "WIN_7"
		ConsoleWrite("Windows 7 detected"& @CRLF)
		logprint("Windows 7 detected")
		;Set Depdendancy for service startup
		;$aDependency[0] = "WLAN AutoConfigi"
		$aDependency[0] = ""

	Case Else
		ConsoleWrite("Unsupported OS: "& @OSVersion & @CRLF)
		logprint("Unsupported OS: "& @OSVersion)
		Exit
EndSwitch

If $cmdline[0] > 0 Then
    Switch $cmdline[1]
		Case "-i"
			if @OSVersion = "WIN_XP" Then
				;Update Wlan API for WINXP SP3 is needed
				_Update_WlanAPI()
			EndIf
			ConsoleWrite("Installing script" & @CRLF)
            InstallService()
        Case "-u"
			ConsoleWrite("Uninstalling script" & @CRLF)
            RemoveService()
        Case "-r"
			ConsoleWrite("Restarting script" & @CRLF)
            _Service_Stop($sServiceName)
            Sleep(2000)
            _Service_Stop($sServiceName)
            Sleep(1000)
            _Service_Start($sServiceName)
        Case Else
			ConsoleWrite(" - - - Help - - - " & @CRLF)
			ConsoleWrite("params : " & @CRLF)
			ConsoleWrite(" -i : install service" & @CRLF)
			ConsoleWrite(" -u : remove service" & @CRLF)
			ConsoleWrite(" -r : restarting service" & @CRLF)
			ConsoleWrite(" - - - - - - - - " & @CRLF)
            Exit
    EndSwitch
Else
    _Service_init($sServiceName)
EndIf

Func _main($iArg, $sArgs)
	Local $asProfileList
	Local $bCSD63_Found
	Local $sProfile
	Local $file
	local $sError
	local $aInterfaces
	local $sReason
	local $vQuery
	local $sRadioState
	local $sRadioOn
	Local $sDefaultKey

	$bServiceRunning = True
    If Not _Service_ReportStatus($SERVICE_RUNNING, $NO_ERROR, 0) Then
        _Service_ReportStatus($SERVICE_STOPPED, _WinAPI_GetLastError(), 0)
		$bServiceRunning = False
	EndIf

	;Check for Wirelss Cards

	$aInterfaces = _Wlan_StartSession()
	$bServiceActive = True
	If @error Then
		logprint("Failed to start wifi session!")
		$bServiceActive = False
	Elseif UBound($aInterfaces) = 0 Then
		logprint("No Wireless Card Installed!")
		$bServiceActive = False
	Else
		logprint($aInterfaces[0][0])
	EndIf

	;Check to see if Auto Confid is on
	if not _Wifi_AutoConfig() Then
		logprint("Wifi Auto Config is not ON");
		$bServiceActive = False
	EndIf

	If _Service_QueryType("NoveapEvent") = 0 Then
		logprint("Novel 802.1x is tab is not enabled")
		$bServiceActive = False
	EndIf

	$sRadioOn = "Unknown"
	$sDefaultKey = RegEnumVal("HKEY_LOCAL_MACHINE\SOFTWARE\Novell\Location Profiles\Profiles\Default\Instances", 1)
	if @error then
		logprint("Error determining key : " & @error)
		$bServiceActive = False
	EndIf
	logprint("$sDefaultKey = " & $sDefaultKey)

	if not $bServiceActive Then
		logprint("Service is not active:  Wifi not setup")
	EndIf

    While $bServiceRunning

		If $bServiceActive then

			$sRadioState = _WifiOnTest()

			If $sRadioState = "HardWare OFF" Then
				;Radio is turned off
				if $sRadioOn <> "OFF" Then
					Logprint("Turn off 802.1x novell loging");
					$sRadioOn = "OFF"
					if (@OSVersion = "WIN_XP") Then
						RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Novell\Location Profiles\Services\"&$sDefaultKey&"\Default\Tab4","Enable EAP","REG_DWORD",0)
					Else
						RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Novell\Login\Profiles\System\Default\Tab5","Enable EAP","REG_DWORD",0)
					EndIf
				EndIf
			Else
				;Radio is ON
				if $sRadioOn <> "ON" Then
					$sRadioOn = "ON"
					if (@OSVersion = "WIN_XP") Then
						RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Novell\Location Profiles\Services\"&$sDefaultKey&"\Default\Tab4","Enable EAP","REG_DWORD",1)
					Else
						RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Novell\Login\Profiles\System\Default\Tab5","Enable EAP","REG_DWORD",1)
					EndIf
				EndIf

				;get list of wireless profiles
				$asProfileList = _Wlan_GetProfileList()

				$bCSD63_Found = False
				for $i = 0 to UBound($asProfileList)-1
					if $asProfileList[$i] = "CSD63" Then
						$bCSD63_Found = True
						if $i > 0 Then
							;Profle is set, but is not the top profile
							_Wlan_SetProfilePosition("CSD63", 0)
							If @error Then logprint("Could not Set CSD63 position to 0")
						EndIf
					ElseIf  $asProfileList[$i] = "AVAN" Then
						_Wlan_DeleteProfile("AVAN");
					EndIf
				Next

				if not $bCSD63_Found Then
					;Profile is not set.  Create profile using Saved XML file

					if FileExists(@ScriptDir & "\CSD63.XML") Then

						$file = FileOpen(@ScriptDir & "\CSD63.XML", 0)
						If @error Then Return logprint("!FileOpen Error err[" & @error & "]")
						$sProfile = FileRead($File)
						FileClose($File)

						$sError = _Wlan_SetProfile($sProfile,$sReason)
						If @error Then
							logprint("Error creating CSD63 Profile : " & $sError)
						else
							logprint("Created CSD63 Profile")
						EndIf
					Else
						logprint("Profile for CSD63 WIFI network cannot be created. CSD63.XML Cannot be found.")
					EndIf
				EndIf
			EndIf
		EndIf

		;logprint("test");
		_sleep(1000)
	WEnd

	;Close the Wireless Session
	logprint("Exit Wlan Session")
	_Wlan_EndSession()

	;_sleep(1000)
	;Close the service Handles
	logprint("Close servie handles")
	_Service_ReportStatus($SERVICE_STOP_PENDING, $NO_ERROR, 1000)
    DllCallbackFree($tServiceMain)
    DllCallbackFree($tServiceCtrl)

	;_sleep(1000)
    _Service_ReportStatus($SERVICE_STOPPED, $NO_ERROR, 0)
    DllClose($hAdvapi32_DLL)
    DllClose($hKernel32_DLL)

EndFunc   ;==>main

;;;;;;;;;;;;;;;;;;;;;---_Update_WlanAPI()---;;;;;;;;;;;;;;;;;;;;;
Func _Update_WlanAPI()
	Switch @OSLang
		Case "040c","0c0c"
			ConsoleWrite("French Detected"& @CRLF)
			ConsoleWrite("Wlanapi.dll File Version: "& FileGetVersion(@SystemDir&"\Wlanapi.dll") & @CRLF)
			if FileGetVersion(@SystemDir&"\Wlanapi.dll") <> "5.1.2600.5684" Then
				if FileExists(@ScriptDir & "\WindowsXP-KB958071-x86-FRA.exe") Then
					ConsoleWrite("Updating Wlanapi.dll"& @CRLF)
					$Wlanapi_result = RunWait(@ScriptDir & "\WindowsXP-KB958071-x86-FRA.exe /quiet /noreboot")
					ConsoleWrite("Updating Wlanapi.dll Complete: Result " & $Wlanapi_result & @CRLF)
				Else
					ConsoleWrite("Cannot find file: WindowsXP-KB958071-x86-ENU.exe" & @CRLF)
					logprint("Cannot find file: WindowsXP-KB958071-x86-ENU.exe")
					Exit
				EndIf
			Else
				ConsoleWrite("Wlanapi.dll uptodate"& @CRLF)
			EndIf
		Case "0409", "1009"
			ConsoleWrite("English Detected"& @CRLF)
			ConsoleWrite("Wlanapi.dll File Version: "& FileGetVersion(@SystemDir&"\Wlanapi.dll") & @CRLF)
			if FileGetVersion(@SystemDir&"\Wlanapi.dll") <> "5.1.2600.5684" Then
				if FileExists(@ScriptDir & "\WindowsXP-KB958071-x86-ENU.exe") Then
					ConsoleWrite("Updating Wlanapi.dll"& @CRLF)
					$Wlanapi_result = RunWait(@ScriptDir & "\WindowsXP-KB958071-x86-ENU.exe /quiet /noreboot")
					ConsoleWrite("Updating Wlanapi.dll Complete: Result "&$Wlanapi_result& @CRLF)
				Else
					ConsoleWrite("Cannot find file: WindowsXP-KB958071-x86-ENU.exe" & @CRLF)
					logprint("Cannot find file: WindowsXP-KB958071-x86-ENU.exe")
					Exit
				EndIf
			Else
				ConsoleWrite("Wlanapi.dll uptodate"& @CRLF)
			EndIf
		Case Else
			ConsoleWrite("Unsupported Language: "&@OSLang& @CRLF)
			logprint("Unsupported Language: "&@OSLang)
			Exit
	EndSwitch
EndFunc

;;;;;;;;;;;;;;;;;;;;;---_Wifi_AutoConfig()---;;;;;;;;;;;;;;;;;;;;;
Func _Wifi_AutoConfig()
	Local $QI
	$QI = _Wlan_QueryInterface($WLAN_INTF_OPCODE_AUTOCONF_ENABLED)
	If @error Then logprint("_Wlan_QueryInterface(0) Error")
	If $QI = "Auto Config Enabled" Then
		Return True
	Else
		Return False
	EndIf
EndFunc

;;;;;;;;;;;;;;;;;;;;;---_WifiOnTest()---;;;;;;;;;;;;;;;;;;;;;
Func _WifiOnTest()
	local $vQuery
	local $sResult

	if @OSVersion = "WIN_XP" Then
		$vQuery = _Wlan_GetNetworks()
		if @error=3 then
			$sResult = "Hardware OFF"
		Else
			$sResult = "Hardware ON"
		EndIf
	Else
		$vQuery = _Wlan_QueryInterface($WLAN_INTF_OPCODE_RADIO_STATE)
		$sResult = $vQuery[0][2]
	EndIf

	Return $sResult
EndFunc




;;;;;;;;;;;;;;;;;;;;;---_Sleep()---;;;;;;;;;;;;;;;;;;;;;
Func _Sleep($delay)
    Local $result = DllCall($hKernel32_DLL, "none", "Sleep", "dword", $delay)
EndFunc

;;;;;;;;;;;;;;;;;;;;;---InstallService()---;;;;;;;;;;;;;;;;;;;;;
Func InstallService()
    #RequireAdmin

    _Service_Create(	$sServiceName, $sDisplayName, $SERVICE_WIN32_OWN_PROCESS, _
						$SERVICE_AUTO_START, $SERVICE_ERROR_SEVERE, _
						'"' & @ScriptFullPath & '"' ,"" ,""); ,$aDependency)
    If @error Then
        ConsoleWrite("InstallService(): Problem installing service, Error number is " & @error & @CRLF & " message : " & _WinAPI_GetLastErrorMessage() & @CRLF)
    Else
        ConsoleWrite("InstallService(" & $sServiceName & "): Installation of service successful" & @CRLF)
		_Service_SetDesc($sServiceName,$sDescription);
		_Service_Start($sServiceName);
    EndIf
EndFunc

;;;;;;;;;;;;;;;;;;;;;---RemoveService()---;;;;;;;;;;;;;;;;;;;;;
Func RemoveService()
    _Service_Stop($sServiceName)
    _Service_Delete($sServiceName)
EndFunc

;;;;;;;;;;;;;;;;;;;;;---logprint()---;;;;;;;;;;;;;;;;;;;;;
Func logprint($textMessage)
	If Not FileExists($MainLog) Then FileWriteLine($MainLog, "Log created: " & @YEAR & "-" & @MON & "-" & @MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC)
	FileWriteLine($MainLog, @YEAR & "-" & @MON & "-" & @MDAY & " " & @HOUR & ":" & @MIN & ":" & @SEC & " [" & @AutoItPID & "] >> " & $textMessage & @CRLF)
EndFunc

;;;;;;;;;;;;;;;;;;;;;---_ExitAutoIt()---;;;;;;;;;;;;;;;;;;;;;
Func _ExitAutoIt()

EndFunc
